

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/login")
public class login extends HttpServlet {
	private static final long serialVersionUID = 1L;
   public login() throws ClassNotFoundException, SQLException {
        super();
        Class.forName ("org.sqlite.JDBC");
 		
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		try {
			Connection conn = DriverManager.getConnection("jdbc:sqlite:cms.db");
			PreparedStatement preStatement = conn.prepareStatement("select uname , pass from users where uname = ? and pass= ? ;");
		    String name=request.getParameter("username");
		    String pass=request.getParameter("password");
		    preStatement.setString(1, name);
		    preStatement.setString(2, pass);
		    ResultSet res=preStatement.executeQuery();
		    String user=res.getString(1);
		    if(res.next())
		    {
		    	HttpSession session=request.getSession();
		    	session.setAttribute("name",user);
		    	request.setAttribute("name",user);
		    	if(user.equals("admin") && res.getString(2).equals("admin"))
		    	{
		    		
		    	    request.getRequestDispatcher("admin.jsp").forward(request, response);
		    	}
		    	else if(user.equals(name) && res.getString(2).equals(pass))
		    	{
		    		 request.getRequestDispatcher("main.jsp").forward(request, response);
		   
		    	}
		    	else
		    	{
		    		response.sendRedirect("welcome.jsp");
		    	}
		    }
		    else
		    	response.sendRedirect("welcome.jsp");
		    preStatement.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
}

